package _dp_base;

import _object.TreeNode;

/**
 * 337. 打家劫舍 III
 */
public class No337 {
    /*
      一、状态机DP
     */

    /**
     * 1. 递归
     */
    public int rob1(TreeNode root) {
        return Math.max(dfs(root, 0), dfs(root, 1));
    }

    private int dfs(TreeNode node, int selected) {
        if (node == null) return 0;
        else if (selected == 1) return dfs(node.left, 0) + dfs(node.right, 0) + node.val;
        else return Math.max(dfs(node.left, 0), dfs(node.left, 1)) + Math.max(dfs(node.right, 0), dfs(node.right, 1));
    }

    /*
      二、树形DP
     */
    public int rob2(TreeNode root) {
        int[] res = dfs(root);
        return Math.max(res[0], res[1]); // 根节点选或不选的最大值
    }

    private int[] dfs(TreeNode node) {
        if (node == null) // 递归边界
            return new int[]{0, 0}; // 没有节点，怎么选都是 0
        int[] left = dfs(node.left);  // 递归左子树
        int[] right = dfs(node.right); // 递归右子树
        int rob = left[1] + right[1] + node.val; // 选
        int notRob = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);  // 不选
        return new int[]{rob, notRob};
    }
}
